//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.yuebanmaoshare.file.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImgUtil {
    private static Logger logger = LoggerFactory.getLogger(ImgUtil.class);

    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
        if (imageBytes != null && imageBytes.length > 0 && (long)imageBytes.length >= desFileSize * 1024L) {
            long srcSize = (long)imageBytes.length;
            double accuracy = 0.4;

            try {
                while((long)imageBytes.length > desFileSize * 1024L) {
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                    Thumbnails.of(new InputStream[]{inputStream}).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);
                    imageBytes = outputStream.toByteArray();
                }

                logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb", new Object[]{imageId, srcSize / 1024L, imageBytes.length / 1024});
            } catch (Exception e) {
                logger.error("【图片压缩】msg=图片压缩失败!", e);
            }

            return imageBytes;
        } else {
            return imageBytes;
        }
    }

    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900L) {
            accuracy = (double)0.5F;
        } else if (size < 2047L) {
            accuracy = 0.6;
        } else if (size < 3275L) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }

        return accuracy;
    }
}
